import { NextRequest, NextResponse } from 'next/server'
import { readPos, writePos } from '@/lib/data'
import { verifyToken } from '@/lib/auth'

export async function PUT(request: NextRequest, { params }: { params: { id: string } }) {
	try {
		const token = request.cookies.get('token')?.value
		const decoded = verifyToken(token || '')
		if (!decoded || !decoded.isAdmin) {
			return NextResponse.json({ success: false, message: '需要管理员权限' }, { status: 403 })
		}
    const { key, name, englishName, description } = await request.json()
		const items = readPos()
		const item = items.find(i => i.id === params.id)
		if (!item) return NextResponse.json({ success: false, message: '词性不存在' }, { status: 404 })
		if (key && key !== item.key && items.some(i => i.key === key)) {
			return NextResponse.json({ success: false, message: 'key 已存在' }, { status: 400 })
		}
    if (key) item.key = key
    if (name) item.name = name
    if (englishName !== undefined) item.englishName = englishName || undefined
    if (description !== undefined) item.description = description || undefined
		writePos(items)
		return NextResponse.json({ success: true, item })
	} catch (e) {
		return NextResponse.json({ success: false, message: '更新词性失败' }, { status: 500 })
	}
}

export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
	try {
		const token = request.cookies.get('token')?.value
		const decoded = verifyToken(token || '')
		if (!decoded || !decoded.isAdmin) {
			return NextResponse.json({ success: false, message: '需要管理员权限' }, { status: 403 })
		}
		const items = readPos()
		const remained = items.filter(i => i.id !== params.id)
		writePos(remained)
		return NextResponse.json({ success: true })
	} catch (e) {
		return NextResponse.json({ success: false, message: '删除词性失败' }, { status: 500 })
	}
}
